//index.js
const api = require('../../utils/api.js');
const regeneratorRuntime = require('../../utils/runtime.js');
const app = getApp()

const util = require('../../utils/utils.js');
// index/list.js

//banner
Page({
  data: {
    //条件
    tabLabels: ['学校', '专业', '年级'],
    tab: [false, false, false],
    _college_id: 0,
    _major_id: 0,
    _grade_id: 0,
    currentTab: -1,
    colleges: [],
    majors: [],
    grades: ['大一', '大二', '大三', '大四', '大五', '研一', '研二'],
    allMajors: [],
    posts: [],
    page: 1,
    nodata: false,
    nomore: false,
    where: {
      college: {},
      isShow: 1
    },
  },

  onLoad: async function (options) {
    this.loadCondition();
    await this.loadDataList(this.data.where);
  },

  onPullDownRefresh: async function(e) {
    let that = this;
    let page = 1
    that.setData({
      page: page,
      posts: [],
      nomore: false,
      nodata: false
    })
    await this.loadDataList(that.data.where)
    wx.stopPullDownRefresh();
  },

  onReachBottom: async function(e) {
    let where = this.data.where
    await this.loadDataList(where)
  },

  loadCondition: async function() {
    var colleges = [], majors=[], grades = [];
    let res = await api.getCollegeList(1, {})
    if (res.data.length > 0) {
      this.setData({
        colleges: this.data.colleges.concat(res.data),
      });
    }
    // res = await api.getGradeList(1, {})
    // if (res.data.length > 0) {
    //   this.setData({
    //     grades: this.data.grades.concat(res.data),
    //   });
    // }

    res = await api.getMajorList(1, {})
    if (res.data.length > 0) {
      let ms = []
      for (var i in res.data) {
        ms.push(res.data[i].name)
      }
      this.setData({
        majors: ms,
        allMajors: ms,
      });
    }
  },
  //
  hideCondition: function () {
    this.setData({
      displays: "none"
    })
  },
  showCondition: function () {
    this.setData({
      displays: "block"
    })
  },

  filterTab: function(e) {
    var index = e.currentTarget.dataset.index;
    this.switchCondition(index);
  },

  switchCondition: function(index) {
    var data = [false, false, false];
    if (typeof (index) == 'undefined') {
      this.setData({
        tab: data,
        currentTab: -1,
      });
      this.hideCondition();
      return;
    }
    data[index] = !this.data.tab[index];
    this.setData({
      tab: data,
      currentTab: index
    });
    if (data[index]) {
      this.showCondition();
    } else {
      this.hideCondition();
    }
  },

  //筛选项点击操作
  doFilter: function (e) {
    var currentTab = this.data.currentTab;
    var self = this, id = e.currentTarget.dataset.id, index = e.currentTarget.dataset.index, name = e.currentTarget.dataset.name, tabTxt = this.data.tabLabels;
    this.hideCondition();
    let where = self.data.where
    console.log(currentTab + ',' + id + ',' + name );
    switch (currentTab) {
      case 0:
        let ms = self.data.allMajors
        if (self.data._college_id == id) {
          tabTxt[currentTab] = '学校';
          id = 0;
          where.college.name = ''
        } else {
          let colleges = this.data.colleges
          tabTxt[currentTab] = util.abbr(name, 4);
          where.college.name = name
          ms = colleges[index].majors
        }
        self.setData({
          _college_id: id,
        });
        
        break;
      case 1:
        if (self.data._major_id == id) {
          tabTxt[currentTab] = '专业';
          id = 0;
          where.college.major = ''
        } else {
          tabTxt[currentTab] = util.abbr(name, 5);
          where.college.major = name
        }
        self.setData({
          _major_id: id,
        });
        
        break;
      case 2:
        if (self.data._grade_id == id) {
          tabTxt[currentTab] = '年级';
          id = 0;
          where.college.grade = ''
        } else {
          tabTxt[currentTab] = util.abbr(name, 4);
          where.college.grade = name
        }
        self.setData({
          _grade_id: id,
        });
        break;
    }
    self.setData({
      tab: [false, false, false],
      tabLabels: tabTxt,
      where: where,
      page: 1,
      nomore: false,
      nodata: false,
      posts: [],
    });
    //数据筛选
    self.loadDataList(where);
  },

  loadDataList: async function (filter) {
    if (filter === undefined) {
      filter = {}
    }
    wx.showLoading({
      title: '加载中...',
    })
    let that = this
    let page = that.data.page
    if (that.data.nomore) {
      wx.hideLoading()
      return
    }
    let result = await api.getNewPostsList(page, filter)
    if (result.data.length === 0) {
      that.setData({
        nomore: true
      })
      if (page === 1) {
        that.setData({
          nodata: true
        })
      }
    }
    else {
      let urlData = result.data
      for (var i in urlData) {
        urlData[i].image = api.convertCloud2Http(urlData[i].image)
      }
      that.setData({
        page: page + 1,
        posts: that.data.posts.concat(urlData),
      })
    }
    wx.hideLoading()
  },

  likeClick: function(e) {
    var idx = e.currentTarget.dataset.index;
    console.log('click -> ' + idx);
    var details = this.data.details;
    var uId = 1;
    if (details[idx].like.users.includes(uId)) {
      details[idx].like.users.forEach(function(item, index, arr) {
          if (item == uId) {
            arr.splice(index, 1);
            console.log('delete -> ' + item);
          }
      });
      details[idx].like.num = details[idx].like.num - 1;
      details[idx].isLike = 0;
    } else {
      details[idx].like.users.push(uId);
      details[idx].like.num = details[idx].like.num + 1;
      details[idx].isLike = 1;
    }
    console.log(details);
    this.setData({
      posts: posts,
    });
  },

  conditChange: function(e) {
    console.log(e);
    var index = e.detail.current;
    var currentTab = this.data.currentTab;
    if (index == currentTab) {
      return;
    }
    this.switchCondition(index);
  },

  navigateToDetail: function(e) {
    let id = e.currentTarget.id
    wx.navigateTo({
      url: '../detail/detail?id=' + id,
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function (data) {
          console.log(data)
        },
        someEvent: function (data) {
          console.log(data)
        }
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据
        //res.eventChannel.emit('acceptDataFromOpenerPage', {data: 'test' })
        api.addPostView({postId: id})
      }
    })
  }
})